<template>
	<view class="container" :style="{backgroundImage}">
		<uv-navbar title="登录" bg-color="rgba(0,0,0,.0)" left-icon-color="#fff" :title-style="{color: '#fff'}"
			@left-click="navBack" />
		<uv-loading-page :loading="loadingPage" loading-text="加载中..." font-size="24rpx" />
		<view v-if="isFirst" class="select-role">
			<view class="title">请选择您的角色</view>
			<view class="desc">进入相应的用户端</view>
			<view class="roles-box">
				<view class="fs-box" :class="{activity: role === 'fs'}" @click="changeRole('fs')">
					<view class="name">飞手</view>
					<view class="img-box">
						<uv-image width="100%" mode="widthFix" :src="`${$hd.baseUrl}/images/login/img-fs@3x.png`" />
					</view>
					<view class="selectd">
						<uv-image width="100%" mode="widthFix" :src="`${$hd.baseUrl}/images/login/icon-ch@3x.png`" />
					</view>
				</view>
				<view class="nh-box" :class="{activity: role === 'farmer'}" @click="changeRole('farmer')">
					<view class="name">农户</view>
					<view class="img-box">
						<uv-image width="100%" mode="widthFix" :src="`${$hd.baseUrl}/images/login/img-nh@3x.png`" />
					</view>
					<view class="selectd">
						<uv-image width="100%" mode="widthFix" :src="`${$hd.baseUrl}/images/login/icon-ch@3x.png`" />
					</view>
				</view>
			</view>
			<view class="to-login" @click="showLogin">
				<uv-image width="16px" mode="widthFix" :src="`${$hd.baseUrl}/images/login/icon-go@3x.png`" />
			</view>
		</view>
		<view v-else class="wrapper">
			<view class="logo-box">
				<uv-image width="75" height="75"
					:src="`${$hd.baseUrl}/images/login/logo${role === 'fs' ? '' : '-n'}@3x.png`" />
			</view>
			<view class="title">欢迎使用桂鸟农服</view>
			<view class="login-btn" v-if="toggleLogin">
				<uv-button type="primary" shape="circle" :loading="logining"
					:color="role === 'fs' ? '#006BFE' : '#0CCA89'" text="手机号快速验证" open-type="getPhoneNumber"
					@getphonenumber="getphonenumber" />
				<view @tap="toggle" class="text-center margin-top"
					:style="{color: role === 'fs' ? '#006BFE' : '#0CCA89'}">使用账号密码登录</view>
			</view>
			<view v-if="!toggleLogin"
				style="display: flex;flex-direction: column;align-items: center;width: 100%;height: 400px;margin-top: 10%;">
				<uv-form style="width: 80%" labelWidth="10" :model="formData" :rules="rules" ref="form">
					<uv-form-item prop="username">
						<uv-input :custom-style="customStyle" v-model="formData.username" placeholder="手机号"></uv-input>
					</uv-form-item>
					<uv-form-item prop="password">
						<uv-input v-model="formData.password" :password="showPassword" placeholder="密码"
							:custom-style="customStyle">
							<template slot="suffix">
								<uv-icon :name="showPassword ? 'eye-off' : 'eye-fill'" size="24"
									@click="showPassword = !showPassword" />
							</template>
						</uv-input>
					</uv-form-item>
				</uv-form>
				<uv-button :customStyle="{width:'90%',marginTop:'20%'}" type="primary" :loading="logining"
					:color="role === 'fs' ? '#006BFE' : '#0CCA89'" text="登录" @tap="submit" />
				<view @tap="toggle" class="text-center margin-top"
					:style="{color: role === 'fs' ? '#006BFE' : '#0CCA89'}">手机号快速验证</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		encrypt
	} from '@/utils/jsencrypt'

	export default {
		data() {
			return {
				customStyle: {
					width: '600rpx',
					background: '#fff',
					borderRadius: '16rpx'
				},
				logining: false,
				loadingPage: false,
				isFirst: false,
				backgroundImage: `url(${this.$hd.baseUrl}/images/login/bg-login@3x.png)`,
				role: 'farmer',
				showPassword: true,
				toggleLogin: true,
				formData: {
					"username": '',
					"password": ''
				},
				rules: {
					'username': {
						type: 'string',
						required: true,
						message: '请填写账号',
						trigger: ['blur', 'change']
					},
					'password': {
						type: 'string',
						required: true,
						message: '请填写密码',
						trigger: ['blur', 'change']
					}
				}
			}
		},
		onLoad() {
			if (uni.getStorageSync("login-type")) {
				this.isFirst = false;
				this.role = uni.getStorageSync("login-type")
			} else {
				uni.setStorageSync("login-type", this.role)
			}
			this.$store.dispatch('themeState/setThemeAction', this.role)

			if (this.isFirst) {
				this.backgroundImage = `url(${this.$hd.baseUrl}/images/login/bg-role@3x.png)`
			}
			uni.removeStorageSync('token');
		},
		methods: {
			changeRole(r) {
				this.role = r
				uni.setStorageSync("login-type", r);
				this.$store.dispatch('themeState/setThemeAction', r)
			},
			toggle() {
				this.toggleLogin = !this.toggleLogin
			},
			submit() {
				let _this = this;
				this.$refs.form.validate().then(result => {
					const password = encrypt(_this.formData.password)
					_this.$http.post('/login', {}, {
						data: {
							..._this.formData,
							password
						}
					}).then(res => {
						if (res.code != 200) {
							uni.$uv.toast(res.msg)
							return;
						}
						this.fetchOpenId()
						
						uni.setStorageSync("token", res.token);
						this.goBack()
					})
				}).catch(errors => {
					uni.showToast({
						icon: 'error',
						title: '请填写完整信息'
					})
				})
			},
			goBack() {
				if(getCurrentPages().length>=2) {
					uni.navigateBack()
				} else {
					uni.reLaunch({
						url: '/pages/index/index'
					})
				}
			},
			// 登陆后获取openId
			fetchOpenId() {
				// 触发获取用户信息
				this.$store.dispatch('user/setUserAction')
				const that = this
				// 获取openId
				wx.login({
					success(res) {
						console.log('login code:', res.code)
						console.log('current role (theme):', that.role)

						that.$http.get('/wechat/mini/session', {
							params: {
								code: res.code,
								theme: that.role
							}
						}).then(data => {
							console.log('openId:', data)
							uni.setStorageSync('openId', data.data)
						})
					}
				})
			},
			navBack() {
				// uni.navigateBack();
				// this.isFirst = true
				uni.reLaunch({
					url: "/pages/index/index"
				})
			},
			getphonenumber(e) {
				if (e.errMsg === "getPhoneNumber:ok") {
					this.logining = true
					uni.$uv.http.get(`/login/${e.code}/${this.role}`).then((res) => {
						this.logining = false
						if (res.code !== 200) {
							uni.$uv.toast(res.msg)
							return
						}
						uni.setStorageSync("token", res.data);
						this.fetchOpenId()

						// const formData = uni.getStorageSync('formData');
						// if (formData) {
						// 	console.log('跳到目标:', `/subPages/pages/bookOrder/index?formData=${JSON.stringify(formData)}`);
						// 	// uni.navigateTo({
						// 	// 	url: `/subPages/pages/bookOrder/index`
						// 	// });
						// 	uni.reLaunch({
						// 		url: `/subPages/pages/bookOrder/index`
						// 	});
						// 	console.log('1111');
						// } else {
						// 	uni.reLaunch({
						// 	url: '/pages/index/index',
						// 	});
						// 	console.log('2222',formData);
						// }
						this.goBack()
					}).catch((err) => {
						uni.showToast({
							// icon:'error',
							title: err.msg || err
						})
						this.logining = false;
					});
				}
			},
			showLogin() {
				this.loadingPage = true
				this.isFirst = false
				uni.setStorageSync("login-type", this.role);
				this.$store.dispatch('themeState/setThemeAction', this.role)
				this.backgroundImage =
					`url(${this.$hd.baseUrl}/images/login/bg-login${this.role === 'fs' ? '' : '-n'}@3x.png)`
				setTimeout(() => {
					this.loadingPage = false
				}, 300)
			},
		},
	};
</script>

<style lang="scss">
	page {
		background: #fff;
	}

	.container {
		padding-top: 210px;
		position: relative;
		width: 100vw;
		height: 100vh;
		overflow: hidden;
		background-size: 100% auto;
		background-repeat: no-repeat;

		.select-role {
			margin-top: -35px;

			.title {
				font-size: 24px;
				font-weight: bold;
				text-align: center;
			}

			.desc {
				margin-top: 20px;
				font-size: 14px;
				color: #B8B8B8;
				text-align: center;
			}

			.roles-box {
				display: flex;
				margin: 55px auto 0;
				padding: 0 22px;
				box-sizing: border-box;
				overflow: hidden;
				justify-content: space-between;

				.fs-box,
				.nh-box {
					width: 47%;

					&.activity {
						.img-box {
							border-color: #006BFE;
						}

						.selectd {
							display: block;
						}
					}

					.name {
						font-size: 14px;
						font-weight: bold;
						text-align: center;
						margin-bottom: 12px;
					}

					.img-box {
						border-radius: 16px;
						overflow: hidden;
						border: 2px solid #fff;
					}

					.selectd {
						width: 18px;
						height: 18px;
						background: #006BFE;
						border-radius: 50%;
						margin: 15px auto 0;
						padding: 5px;
						display: none;
					}
				}
			}

			.to-login {
				width: 100px;
				height: 50px;
				background: #006BFE;
				border-radius: 25px;
				margin: 80px auto 0;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}

		.wrapper {
			position: relative;
			z-index: 90;
			padding-bottom: 40upx;

			.logo-box {
				display: flex;
				justify-content: center;
			}

			.title {
				margin-top: 35px;
				text-align: center;
				font-size: 19px;
				font-weight: bold;
			}

			.login-btn {
				width: 280px;
				margin: 80px auto 0;
			}
		}
	}
</style>